package com.qf.usermybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> TL = new ThreadLocal<>();
    static {
        try {
            InputStream reader = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(reader);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取连接
    private static SqlSession openSession(){
        SqlSession session = TL.get();
        if (session == null){
            session = factory.openSession();
            TL.set(session);
        }
        return session;
    }
    //释放连接
    public static void closeSession(){
        SqlSession session = TL.get();
        session.close();
        TL.remove();
    }
    //提交事务
    public static void commit(){
        SqlSession session = openSession();
        session.commit();
        closeSession();
    }
    //回滚事务
    public static void rollback(){
        SqlSession session= openSession();
        session.rollback();
        closeSession();

    }
    //获得接口实现类对象
    public static <T extends Object> T getMaaper(Class<T> clazz){
        SqlSession session = openSession();
        return session.getMapper(clazz);
    }
}
